package com.guiji.quartz.task;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.guiji.quartz.mapper.SpiderNewsMapper;
import com.guiji.quartz.mapper.SpiderNewsStatMapper;
import com.guiji.quartz.mapper.Text2videoConfigMapper;
import com.guiji.quartz.service.ISpiderNewsStatService;
import com.guiji.quartz.service.IText2videoConfigService;
import com.guiji.quartz.vo.CountVo;
import com.guiji.quartz.vo.SpiderNewsStat;
import com.guiji.quartz.vo.Text2videoConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @program: cms-vue-plus
 * @description:
 * @author: gaoX
 * @create: 2021-09-15 18:04
 **/
@Component("countNewsTask")
public class CountNewsTask {
	public static final String pushUrl = "https://oapi.dingtalk.com/robot/send?access_token=1f82e04edc504b7a3c1df0182b97fd156a01c9985cfb3bc9af9439b899a79f4c";

	@Autowired
	SpiderNewsMapper spiderNewsMapper;
	@Autowired
	SpiderNewsStatMapper spiderNewsStatMapper;
	@Autowired
	ISpiderNewsStatService iSpiderNewsStatService;
	@Autowired
	Text2videoConfigMapper text2videoConfigMapper;

	public void countNewsTask() {
		DateTime t1 = DateTime.now();
		DateTime t2 = DateUtil.offsetHour(t1, -1);
		List<SpiderNewsStat> spiderNewsStats = spiderNewsMapper.selectHourNews(t1, t2);
		List<SpiderNewsStat> res = new ArrayList<>();
		spiderNewsStats.forEach(spiderNewsStat -> {
			spiderNewsStat.setCreateTime(t1);
			spiderNewsStat.setStatSign(0);
			spiderNewsStat.setCreateBy("admin");
			res.add(spiderNewsStat);
		});
		iSpiderNewsStatService.saveBatch(res);
	}

	/**
	 * 统计u2b账号对应详细数据
	 *
	 * @param
	 */
	public void pushCountToDingding(Integer n) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		DateTime dateTime = DateUtil.offsetDay(new Date(), n);
		String t = sdf.format(dateTime);
		List<CountVo> countResult = spiderNewsStatMapper.countDetail(t);

		//String key = c1.getBackup3() + "账号:" + c1.getBackup1();
		//查询全部的config配置表,过滤掉为-1的状态
//		QueryWrapper<Text2videoConfig> queryWrapper  =new QueryWrapper();
//		queryWrapper.ne("news_lang","-1");
		List<Text2videoConfig> allConfigs = text2videoConfigMapper.listCV();
		HashMap<String, ArrayList<String>> map = new HashMap();
		for (Text2videoConfig text2videoConfig : allConfigs) {
			String key = text2videoConfig.getBackup3() + "账号:" + text2videoConfig.getBackup1();
			if (map.keySet().contains(key)) {
				ArrayList<String> oldList = map.get(key);
				oldList.add(text2videoConfig.getNewsCategory());
				map.put(key, oldList);
			} else {
				ArrayList<String> oldList = new ArrayList<>();
				oldList.add(text2videoConfig.getNewsCategory());
				map.put(key, oldList);
			}
		}

		Map<String, Object> param = new HashMap<>();
		Map<String, Object> markdown = new HashMap<>();

		String markdown1 = getMarkdown2(map, countResult, t);
		markdown.put("title", "统计报告");
		markdown.put("text", markdown1);
		param.put("msgtype", "markdown");
		param.put("markdown", markdown);
		HttpUtil.post(pushUrl, JSONUtil.toJsonStr(param), 10000);
	}

	private String getMarkdown2(HashMap<String, ArrayList<String>> map, List<CountVo> countResult, String t) {

		List<CountVo> list = new ArrayList<CountVo>();

		StringBuffer stringBuffer = new StringBuffer();
		stringBuffer.append("## " + t + "新闻统计\n[新闻类别:爬取成功,推送成功,推送失败,上限次数]  \n  ");
		for (Map.Entry<String, ArrayList<String>> entey : map.entrySet()) {
			CountVo countvo = getCountCategory(entey, countResult);
			StringBuffer sber = new StringBuffer();
			for (String category : entey.getValue()) {
				CountVo cvDetail = new CountVo(category, 0, 0, 0, 0);
				for (CountVo c1 : countResult) {
					if (c1.getNewsCategory().equals(category)) {
						cvDetail.setDownloadSuccess(c1.getDownloadSuccess());
						cvDetail.setPushSuccess(c1.getPushSuccess());
						cvDetail.setPushFail(c1.getPushFail());
						cvDetail.setShangxian(c1.getShangxian());
					}
				}

				sber.append("- " + cvDetail.getNewsCategory() + "： " + cvDetail.getDownloadSuccess() + " " + cvDetail.getPushSuccess() + " " + cvDetail.getPushFail() + " " + cvDetail.getShangxian() + "  \n  ");
			}
			countvo.setDetails(sber.toString());
			list.add(countvo);
		}
		//按照推送大小降序
//		List<CountVo> soreList = getList(list);
		//过滤掉有推送的，并且按照爬虫数据排序
		Collections.sort(list, (Comparator<CountVo>) (o1, o2) -> o2.getDownloadSuccess() - o1.getDownloadSuccess());
		List<CountVo> soreList = new ArrayList<>();
		list.forEach(cv ->{
			if(cv.getPushSuccess().equals(0)){
				soreList.add(cv);
			}
		});

		String total = getTotal(list);
		stringBuffer.append(total);
		for (int i = 1; i <= soreList.size(); i++) {
			CountVo cvTag =soreList.get(i-1);
			String res;
			if (cvTag.getShangxian() > 0) {
				res =cvTag.getNewsCategory() + "： " + cvTag.getDownloadSuccess() + " " + cvTag.getPushSuccess() + " " + cvTag.getPushFail() + " [已达上限]" + "**  \n  ";
			} else {
				res =cvTag.getNewsCategory() + "： " + cvTag.getDownloadSuccess() + " " + cvTag.getPushSuccess() + " " + cvTag.getPushFail() + "**  \n  ";
			}
			stringBuffer.append("**"+i+". "+res +cvTag.getDetails());
		}
		return stringBuffer.toString();
	}

	private String getTotal(List<CountVo> soreList) {
		int downTotal=0,pushSuccessTotal=0;
		for (int i = 0; i < soreList.size(); i++) {
			downTotal = downTotal+soreList.get(i).getDownloadSuccess();
			pushSuccessTotal = pushSuccessTotal+soreList.get(i).getPushSuccess();
		}
		String res = "**配置爬取总量："+downTotal+"  推送成功总量："+pushSuccessTotal+"**  \n  ";
		return res;
	}


//	public List<CountVo> getList(List<CountVo> list) {
//		Collections.sort(list, new Comparator<CountVo>() {
//			@Override
//			public int compare(CountVo o1, CountVo o2) {
//				//排序属性
//				if (o1.getPushSuccess() < o2.getPushSuccess()) {
//					return 1;
//				}
//				if (o1.getPushSuccess().equals(o2.getPushSuccess())) {
//					return 0;
//				}
//				return -1;
//			}
//		});
//
//		return list;
//	}

	private CountVo getCountCategory(Map.Entry<String, ArrayList<String>> entey, List<CountVo> countResult) {
		CountVo cvTag = new CountVo(entey.getKey(), 0, 0, 0, 0);
		for (String category : entey.getValue()) {
			for (CountVo countVo : countResult) {
				if (countVo.getNewsCategory().equals(category)) {
					cvTag.setDownloadSuccess(cvTag.getDownloadSuccess() + countVo.getDownloadSuccess());
					cvTag.setPushSuccess(cvTag.getPushSuccess() + countVo.getPushSuccess());
					cvTag.setPushFail(cvTag.getPushFail() + countVo.getPushFail());
					cvTag.setShangxian(cvTag.getShangxian() + countVo.getShangxian());
				}
			}
		}
		return cvTag;
	}


}
